package com.hospital.register.user.controller.api;

import com.hospital.register.common.result.Result;
import com.hospital.register.common.utils.AuthContextHolder;
import com.hospital.register.dto.user.UserAuthDto;
import com.hospital.register.dto.user.VerificationCodeDto;
import com.hospital.register.enums.AuthStatusEnum;
import com.hospital.register.user.service.UserInfoService;
import com.hospital.register.vo.user.LoginCodeVo;
import com.hospital.register.vo.user.UserQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户相关操作", description = "面向用户")
@RestController
@RequestMapping("/api/user")
@Validated
public class UserInfoApiController {

    /**
     * 处理用户相关业务
     */
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "验证码登录")
    @PostMapping("/login")
    public Result<LoginCodeVo> login(@RequestBody @Validated VerificationCodeDto param) {
        return Result.ok(this.userInfoService.loginWithVerificationCode(param));
    }

    @ApiOperation(value = "实名认证")
    @PostMapping("/auth/userAuah")
    public Result userAuth(
            @RequestBody @Validated UserAuthDto authInfo,
            @ApiIgnore HttpServletRequest request) {
        authInfo.setId(AuthContextHolder.getUserId(request));
        authInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());//认证中

        if (authInfo.getId() == null) {
            Result result = Result.fail();
            result.setMessage("用户不存在");
            return result;
        }

        this.userInfoService.tryAuthentication(authInfo);
        return Result.ok();
    }

    @ApiOperation(value = "获取当前用户的信息")
    @GetMapping("/auth/getUserInfo")
    public Result<UserQueryVo> getUserInfo(
            @ApiIgnore HttpServletRequest request) {
        Long id = AuthContextHolder.getUserId(request);
        if (id == null) {
            return Result.fail();
        }
        return Result.ok(this.userInfoService.selectById(id));
    }

}
